<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class IndexController extends Controller
{

    /**
     * 返回当前用户
     * @param Request $request
     */
    public function index(Request $request)
    {
//        return 111;
//        dd($request->user());
        return $request->user();
    }

    /**
     * 用户注册
     */
    public function register(Request $request){
        //数据验证
        $rules = [
            'name' => 'required|min:3|alpha_dash|unique:users,name',
            'password' => 'required|min:6',
        ];
        $messages = [
            'name.required' => '请输入用户名',
            'name.min' => '账户不得少于3位',
            'name.alpha_dash' => '账户必须有英文,数字,下划线组成',
            'name.unique' => '该帐号已经存在',
            'password.required' => '请输入密码',
            'password.min' => '密码不得少于6位',
        ];
        if($verify = $this->verify($request->all(), $rules, $messages)) return $verify;
        //通过验证, 处理密码之后, 将用户添加到数据库, 并返回登录token
        $name = $request->input('name');
        $password = $request->input('password');
        //密码加密
        $password_hash = password_hash($password, PASSWORD_BCRYPT);
        //生成登录token
        $token = loginToken();

        // 创建用户
        $data = ['name' => $name, 'password' => $password_hash, 'token' => $token];
        $user = User::create($data);
        $user = collect($user)->only('name', 'token');  //将用户名和登录token返回给客户端
        return $this->success($user);
    }

    /**
     * 用户帐号密码登录
     * 登录成功, 将登录token 添加到数据库, 并返回给用户
     * (后面可以用缓存来做)
     * @param Request $request
     */
    public function login(Request $request){
        //数据验证
        $rules = [
            'name' => 'required|min:3|exists:users,name',
            'password' => 'required|min:6',
        ];
        $messages = [
            'name.required' => '请输入用户名',
            'name.min' => '账户不得少于3位',
            'name.exists' => '账户不存在',
            'password.required' => '请输入密码',
            'password.min' => '密码不得少于6位',
        ];
        if($verify = $this->verify($request->all(), $rules, $messages)) return $verify;
        //验证密码是否正确
        $name = $request->input('name');
        $password = $request->input('password');

        $user = User::where('name', $name)->first();
        if(!$user) return $this->fail('账户不存在');
        if(!password_verify($password, $user->password)){   //验证失败, 返回错误
            return $this->fail('密码错误');
        }
        // 生成登录token
        $user->token = loginToken();
        $user->save();

        return $this->success(collect($user)->only('name', 'token'));
    }
}
